home *** CD-ROM | disk | FTP | other *** search
- Path: news.lpr.carel.fi!usenet
- From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
- Newsgroups: comp.lang.c
- Subject: Re: Source utilities for endian conversion
- Date: Fri, 26 Jan 1996 17:27:25 +0200
- Organization: Carelcomp Forest
- Message-ID: <3108F2DD.1039@cmt.lpr.mail.carel.fi>
- References: <rt9sph42r1m.fsf@topo.nist.gov>
- NNTP-Posting-Host: renoir.cclahti.carel.fi
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b6a (WinNT; I)
-
- Paul J Sullivan wrote:
- >
- > I am trying to write a routine (c is not my first language) that will
- > allow me to read a binary data file on various platforms. I have
- > encountered the -endian problem and, thus, was wondering what routines
- > exist to convert between big- and little- formats. Is it possible to
- > do this without the conversion i.e. somehow specify a directive?? Is
- > it in a FAQ?
- >
-
- Basically, the only difference between little and big endian systems is the way
- numbers are stored. For instance, a 16 bit number 0x1234 (hex) in x86 is stored
- into memory at two adjoining locations: 0x34 and 0x12 (in that order, increasing
- memory address). In Motorola, they are stored into two locations as: 0x12 and
- 0x34 (again, in that order). Similarly, a 32 bit value 0x12345678 in x86 would be
- stored: 0x78, 0x56, 0x34, 0x12 and in Motorola: 0x12, 0x34, 0x56, 0x78. So, when
- you read in a 16 bit value stored in another system, you just swap the most and
- least significant bytes (assuming short is 16 bits and long 32):
-
- unsigned short SwapWord(unsigned short w)
- {
- unsigned char *p = (unsigned char *)&w;
- unsigned char tmp = p[0];
- p[0] = p[1];
- p[1] = tmp;
- return w; /* Surprise! bytes swapped :) */
- }
-
- And, for 32 bits:
-
- unsigned long SwapLong(unsigned long l)
- {
- unsigned short *p = (unsigned short *)&l;
- unsigned short tmp = SwapWord(p[0]);
- p[0] = SwapWord(p[1]);
- p[1] = tmp;
- return l;
- }
-
- Whether the word/long sizes are the same... That's another question. Also, some
- systems _might_ use different floating point formats than others...
-
- HTH,
- AriL
- --
- All my opinions are mine and mine alone.
-